import re
import jwt
from datetime import timedelta,datetime
from rest_framework import serializers

from django.conf import settings
from django_redis import get_redis_connection
from users.models import User

#注册
class CreateUserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码',write_only=True)
    token = serializers.CharField(label='token',read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile', 'token', 'avatar', 'sms_code']

        extra_kwargs ={
            'username':{
                'min_length':4,
                'max_length':20,
                'error_messages':{
                    'min_lenth':'用户名为4-20个字符!',
                    'max_length': '用户名为4-20个字符!',
                }
            },
            'password':{
                'write_only':True,
                'min_length':4,
                'max_length':20,
                'error_messages':{
                    'min_length': '密码为4-20个字符',
                    'max_length': '密码为4-20个字符',
                }
            }
        }

    def validate_mobile(self,value):
        # print(value)
        if not re.match(r'^1[345789]\d{9}$', value):
            raise serializers.ValidationError('手机格式不正确')

        return value

    def validate(self,attrs):
        #创建redis链接对象
        redis_conn = get_redis_connection('verify_code')
        #取出mobile
        mobile = attrs.get('mobile')
        #提取缓存的短信验证码
        redis_sms = redis_conn.get(f'sms_{mobile}')
        #取出前端传过来的验证码
        qianduan_sms = attrs.get('sms_code')

        if redis_sms is None:
            raise serializers.ValidationError('验证码失效')
        if redis_sms.decode().lower() != qianduan_sms.lower():
            raise serializers.ValidationError('验证码错误')
        # print('attrs',attrs)
        return attrs

    def create(self, validated_data):
        # print('validated_data',validated_data)
        del validated_data['sms_code']
        user = super().create(validated_data)

        user.set_password(validated_data['password'])
        # print(user.mobile)
        user.save()



        #设置载体
        payload = {
            'user_id':user.id,
            'username':user.username,
            #设置过期时间为，从现在起的一天
            'exp':datetime.now() + timedelta(days=1)
        }

        #4.加密
        token = jwt.encode(payload,settings.SECRET_KEY,algorithm='HS256')
        #给user这个对象添加一个新属性
        user.token = token.decode()
        return user